/* 
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reactivex.rxjava3.openharmony.schedulers;

import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.openharmony.plugins.RxOpenHarmonyPlugins;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * openharmony-specific Schedulers.
 */
public final class OpenHarmonySchedulers {
    private static final class MainHolder {
        static final Scheduler DEFAULT
                = new HandlerScheduler(new EventHandler(EventRunner.getMainEventRunner()), true);
    }

    private static final Scheduler MAIN_THREAD =
            RxOpenHarmonyPlugins.initMainThreadScheduler(() -> MainHolder.DEFAULT);

    /**
     * A {@link Scheduler} which executes actions on the openharmony main thread.
     * <p>
     *
     * @return The returned scheduler will post asynchronous messages to the looper by default.
     * @see #from(EventRunner, boolean)
     */
    public static Scheduler mainThread() {
        return RxOpenHarmonyPlugins.onMainThreadScheduler(MAIN_THREAD);
    }

    /**
     * A {@link Scheduler} which executes actions on {@code EventRunner}.
     * <p>
     *
     * @param eventRunner to execute the actions on
     * @return The returned scheduler will post asynchronous messages to the EventRunner by default.
     * @see #from(EventRunner, boolean)
     */
    public static Scheduler from(EventRunner eventRunner) {
        return from(eventRunner, true);
    }

    /**
     * A {@link Scheduler} which executes actions on {@code EventRunner}.
     *
     * @param eventRunner to execute the actions on
     * @param async       if true, the scheduler will use async messaging
     * @return the scheduler from the event runner
     * <p>
     * see Message#setAsynchronous(boolean)
     */
    public static Scheduler from(EventRunner eventRunner, boolean async) {
        if (eventRunner == null) {
            throw new NullPointerException("eventRunner == null");
        }
        return new HandlerScheduler(new EventHandler(eventRunner), async);
    }

    private OpenHarmonySchedulers() {
        throw new AssertionError("No instances.");
    }
}